<script setup lang="ts">
/**
 * @author lwlianghehe@gmail.com
 * @date 2025/08/04
 */
import { ref, computed } from "vue";
import { ElDialog, ElButton, ElInput, ElForm, ElFormItem } from 'element-plus';
import { HyperlinkData } from './types';


const props = withDefaults(defineProps<{
  modelValue?: boolean
  title?: string
  width?: string | number
  initialData?: HyperlinkData
}>(), {
  modelValue: false,
  title: '超链接',
  width: '400px',
  initialData: () => ({ text: '', link: '' })
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', data: HyperlinkData): void
  (e: 'cancel'): void
}>()

const formData = ref<HyperlinkData>({
  text: props.initialData.text,
  link: props.initialData.link
})

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val: boolean) => {
    emit('update:modelValue', val)
  }
})

const formRef = ref()

const rules = {
  text: [
    { required: true, message: '请输入文本', trigger: 'blur' }
  ],
  link: [
    { required: true, message: '请输入链接', trigger: 'blur' },
    { 
      pattern: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/, 
      message: '请输入有效的链接地址', 
      trigger: 'blur' 
    }
  ]
}

const handleConfirm = async () => {
  try {
    await formRef.value.validate()
    emit('confirm', formData.value)
    dialogVisible.value = false
  } catch (error) {
    // 验证失败，不关闭对话框
  }
}

const handleCancel = () => {
  emit('cancel')
  dialogVisible.value = false
  // 重置表单数据
  formData.value = {
    text: props.initialData.text,
    link: props.initialData.link
  }
}

// 监听初始数据变化
const resetFormData = () => {
  formData.value = {
    text: props.initialData.text,
    link: props.initialData.link
  }
}

// 当对话框打开时重置数据
const handleOpen = () => {
  resetFormData()
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    :width="width"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    @open="handleOpen">
    
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="80px">
      
      <el-form-item label="文本" prop="text" required>
        <el-input
          v-model="formData.text"
          placeholder="请输入文本"
          clearable />
      </el-form-item>
      
      <el-form-item label="链接" prop="link" required>
        <el-input
          v-model="formData.link"
          placeholder="请输入链接"
          clearable />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
</style>